summaryrefslogtreecommitdiff
path: root/src/pages/api/tasks/[id].ts
blob: 55cc603a4536db3b5f25287c449557b8591d4eb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import type { APIRoute } from 'astro';
import { jsonResponse, getDB, handleAPIError } from '../../../lib/api';

export const prerender = false;

export const PUT: APIRoute = async ({ params, request, locals }) => {
  return handleAPIError(async () => {
    const db = getDB(locals);
    const id = params.id;
    const body = await request.json();
    const { title, description, completed } = body;

    const { results } = await db.prepare(
      'UPDATE tasks SET title = ?, description = ?, completed = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? RETURNING *'
    ).bind(title, description || '', completed || false, id).all();

    if (results.length === 0) {
      return jsonResponse({ error: 'Task not found' }, 404);
    }

    return jsonResponse(results[0]);
  });
};

export const DELETE: APIRoute = async ({ params, locals }) => {
  return handleAPIError(async () => {
    const db = getDB(locals);
    const id = params.id;

    const { success } = await db.prepare('DELETE FROM tasks WHERE id = ?').bind(id).run();

    if (!success) {
      return jsonResponse({ error: 'Task not found' }, 404);
    }

    return jsonResponse({ message: 'Task deleted successfully' });
  });
};